<template>
  <div class="box">
    <!--   【1】logo   -->
    <img class="logo" src="@/assets/images/logo.png" alt="" />
    <!--   【2】登录   -->
    <div class="login">
      <h1 class="title">欢迎登录系统</h1>
      <AForm :model="state.loginData" hideRequiredMark :labelCol="{ span: 0 }" :wrapperCol="{ span: 24 }">
        <AFormItem name="username">
          <AInput v-model:value="state.loginData.username" class="input" :bordered="false" placeholder="请输入您的登录名或手机号">
            <template #prefix><UserOutlined /> </template>
          </AInput>
        </AFormItem>
        <AFormItem>
          <AInputPassword v-model:value="state.loginData.password" class="input" :bordered="false" placeholder="请输入密码">
            <template #prefix><lock-outlined /></template>
          </AInputPassword>
        </AFormItem>
        <AFormItem>
          <div style="display: flex; justify-content: space-between">
            <AInput v-model:value="state.loginData.captchaCode" class="input" style="width: 234px" :bordered="false" placeholder="请输入验证码">
              <template #prefix><SafetyCertificateOutlined /></template>
            </AInput>
            <img class="captcha" :src="state.captchaImg" alt="" @click="getCaptchaFn" />
          </div>
        </AFormItem>
      </AForm>
      <Button class="btn" type="primary" :loading="state.btnLoading" @click="handleLoginBtnClick">登录</Button>
    </div>
    <!--   【3】页脚   -->
    <div class="footer" @click="handlePathTurn">
      <Space :size="20">
        <span>北京宏诚创新科技有限公司</span>
        <span>地址：北京市通州区信创园B区1号楼</span>
      </Space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { LockOutlined, UserOutlined, SafetyCertificateOutlined } from '@ant-design/icons-vue';
import Button from '@/framework/components/basic/button/button.vue';
import { reactive } from 'vue';
import { message, Modal, Space } from 'ant-design-vue';
import { RouteRecordRaw, useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import { getCaptcha } from '@/api/login';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const state = reactive({
  loginData: {
    username: '',
    password: '',
    captchaCode: '',
    code: '',
  },
  captchaImg: '',
  btnLoading: false,
});

const getCaptchaFn = async () => {
  try {
    const res = await getCaptcha();
    state.loginData.captchaCode = '';
    state.captchaImg = res.result.imgBase64;
    state.loginData.code = res.result.code;
  } catch {
    state.loginData.code = 'undefined';
  }
};
getCaptchaFn();

const getFirstRouteName = (list: RouteRecordRaw[]) => {
  for (let item of list) {
    if (item.meta?.hideInMenu) {
      continue;
    }
    if (item.children && item.children.length) {
      return getFirstRouteName(item.children);
    } else {
      return item.name;
    }
  }
};

const handleLoginBtnClick = async () => {
  /*验证*/
  const isEmpty = Object.values(state.loginData).some((item) => !item || item?.trim().length <= 0);
  if (isEmpty) {
    return message.warn('登录信息不能为空！');
  }
  /*登录*/
  state.btnLoading = true;
  try {
    const res = await userStore.login(state.loginData);
    const menu = res?.menus;
    const firstRouteName = getFirstRouteName(menu!);
    setTimeout(() => {
      if (route.query.redirect) {
        router.replace(route.query.redirect as string);
      } else {
        router.replace({
          name: firstRouteName || 'home',
        });
      }
    });
    message.success('登录成功！');
  } catch (err: any) {
    Modal.error({
      title: () => '提示',
      content: () => err.message,
    });
    await getCaptchaFn();
  } finally {
    state.btnLoading = false;
    message.destroy();
    window.removeEventListener('keyup', handleEnter);
  }
};

const handlePathTurn = () => {
  window.open('https://www.honortrends.com/');
};

/**
 * 登录事件
 */
const handleEnter = (e) => {
  if (e.key === 'Enter' && Object.values(state.loginData).every((item) => item)) {
    handleLoginBtnClick();
  }
};
window.addEventListener('keyup', handleEnter);
//
// const keyCode = {
//   61: true,
//   107: true, // 数字键盘 +
//   109: true, // 数字键盘 -
//   173: true, // 火狐 - 号
//   187: true, // +
//   189: true, // -
// };
// // 覆盖 'ctrl'/'command' + ‘+’/‘-’
// document.onclick = function (event) {
//   const ctrlKey = event.ctrlKey || event.metaKey;
//   if (ctrlKey && keyCode[event.keyCode]) {
//     event.preventDefault();
//   } else if (event.detail) {
//     // Firefox
//     event.returnValue = false;
//   }
// };
// // 覆盖鼠标滑动
// document.body.addEventListener(
//   'wheel',
//   (e) => {
//     if (e.ctrlKey) {
//       if (e.deltaY < 0) {
//         e.preventDefault();
//         return false;
//       }
//       if (e.deltaY > 0) {
//         e.preventDefault();
//         return false;
//       }
//     }
//   },
//   { passive: false },
// );
</script>

<style scoped lang="less">
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background: url('@/assets/images/bg.jpg') no-repeat center/100vw 100vh;
  inset-block-start: revert;

  .logo {
    position: fixed;
    left: 9vw;
    top: 6vw;
  }
  .login {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    right: 13vw;
    top: 50%;
    transform: translateY(-50%);
    width: 390px;
    height: 520px;
    .title {
      font-size: 40px;
      color: #395de0;
    }
    .input {
      font-size: 23px;

      :deep(.ant-input) {
        height: 60px;
        margin-left: 15px;
        padding-left: 15px;
        border-bottom: 2px solid #c3cce4;
        font-size: 23px;
        &::-webkit-input-placeholder {
          /* WebKit, Blink, Edge */
          color: #d0def3;
        }
        &:-moz-placeholder {
          /* Mozilla Firefox 4 to 18 */
          color: #d0def3;
        }
        &::-moz-placeholder {
          /* Mozilla Firefox 19+ */
          color: #d0def3;
        }
        &:-ms-input-placeholder {
          /* Internet Explorer 10-11 */
          color: #d0def3;
        }
        &::-ms-input-placeholder {
          /* Microsoft Edge */
          color: #d0def3;
        }
      }
    }
    .captcha {
      width: 160px;
      height: 64px;
    }
    .btn {
      width: 100%;
      height: 64px;
      font-size: 26px;
      color: #fff;
    }
  }
  .footer {
    position: fixed;
    bottom: 25px;
    left: auto;
    right: auto;
    display: flex;
    justify-content: center;
    cursor: pointer;
  }
}
</style>
